//
//  HBChooseView.swift
//  sinaWeibo
//
//  Created by Beans on 16/6/30.
//  Copyright © 2016年 iceWorks. All rights reserved.
//

import UIKit

let HBChooseViewItemMargin: CGFloat = 5
let HBChooseViewItemWH: CGFloat = (kScreenWidth - HomeCellMargin * 2 - HBChooseViewItemMargin * 2) / 3
let HBChooseViewReuseIdentifier = "HBChooseViewCell"

protocol HBChooseViewCellDelegate: NSObjectProtocol {
    func deleteImage(index: NSIndexPath)
}

class HBChooseView: UICollectionView {

    // 定义数组, 保存图片 (私有, 但提供了增加/删除的接口, 防止其它地方直接removeAll()等误操作)
    private lazy var images: [UIImage] = [UIImage]()

    // '加号'的闭包
    var selectImgClosure: (()->())?

    var flowLayout: UICollectionViewFlowLayout = UICollectionViewFlowLayout()

    override init(frame: CGRect, collectionViewLayout layout: UICollectionViewLayout) {
        super.init(frame: frame, collectionViewLayout: flowLayout)
        setupUI()
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

    private func setupUI() {
        backgroundColor = colorWithHexString(hexString: "#CCFFCC", alpha: 1.0)

        flowLayout.itemSize = CGSizeMake(HBChooseViewItemWH, HBChooseViewItemWH)
        flowLayout.minimumInteritemSpacing = HBChooseViewItemMargin
        flowLayout.minimumLineSpacing = HBChooseViewItemMargin

        dataSource = self
        delegate = self
        registerClass(HBChooseViewCell.self, forCellWithReuseIdentifier: HBChooseViewReuseIdentifier)
    }

    // MARK: - 对外方法, 添加图片
    func addImage(image: UIImage) {
        // 添加到数组
        images.append(image)
        // 数据源更改, 刷新
        reloadData()
    }

    // 判断是否多余9张图片
    func isFull() -> Bool {
        return images.count >= 9 ? true : false
    }

    func getImages() -> [UIImage] {
        return images
    }
}

extension HBChooseView: UICollectionViewDataSource, UICollectionViewDelegate, HBChooseViewCellDelegate {
    func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        if images.count == 9 {
            return 9
        } else {
            return images.count + 1     // 最后一个为`加号`
        }
    }

    func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCellWithReuseIdentifier(HBChooseViewReuseIdentifier, forIndexPath: indexPath) as! HBChooseViewCell
//        cell.backgroundColor = color_HSB_Random()

        if indexPath.item == images.count {
            cell.image = UIImage(named: "compose_pic_add")
            cell.deleteImgBtn.hidden = true
        } else {
            cell.image = images[indexPath.item]
            cell.deleteImgBtn.hidden = false
        }

        cell.delegate = self
        cell.index = indexPath
        return cell
    }

    func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {
        // 最后一个cell为'加号', 点击添加图片
        if indexPath.item == images.count {
            printLog("添加图片")
            selectImgClosure?()     // 然后在父视图(publishVC中懒加载本控件时执行choosePicture方法)
        }
    }

    func deleteImage(index: NSIndexPath) {
        // 删除对应的索引, 然后刷新数据
        images.removeAtIndex(index.item)
        reloadData()
    }
}


// MARK: - 自定义cell
class HBChooseViewCell: UICollectionViewCell {

    // 传递的索引
    var index: NSIndexPath?

    weak var delegate: HBChooseViewCellDelegate?

    var image: UIImage? {
        didSet {
            iconView.image = image
        }
    }

    override init(frame: CGRect) {
        super.init(frame: frame)
        setupUI()
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

    private func setupUI() {
        addSubview(iconView)
        addSubview(deleteImgBtn)

        iconView.snp_makeConstraints { (make) -> Void in
            make.edges.equalTo(contentView)
        }
        deleteImgBtn.snp_makeConstraints { (make) -> Void in
            make.top.right.equalTo(contentView)
        }
    }

    @objc private func deleteImgBtnClick(button: UIButton) {
        // 传递索引
        delegate?.deleteImage(index!)
    }

    // MARK: - lazy load
    private lazy var iconView: UIImageView = UIImageView()

    private lazy var deleteImgBtn: UIButton = {
        let button = UIButton(type: .Custom)
        button.setImage(UIImage(named: "compose_photo_close"), forState: .Normal)
        button.sizeToFit()
        button.addTarget(self, action: "deleteImgBtnClick:", forControlEvents: .TouchUpInside)
        return button
    }()
}
